package com.example.demo.store;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: wukangrong
 * @date: 2020/4/22 13:52
 * @description: 仓库
 */
public class Store {
    public static final int MAX = 5;
    public static List<Integer> list = new ArrayList<>();
    public static Lock lock = new ReentrantLock();
    public static Condition con = lock.newCondition();
    public static Condition pro = lock.newCondition();
    public static Semaphore semaphore = new Semaphore(1);



    public static void plus() {
        try {
            semaphore.acquire();
            if (MAX == list.size()) {
                System.out.println("仓库爆满！");
                semaphore.release();
                return;
            }
            list.add(1);
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void minus(){
        try {
            semaphore.acquire();
            if (0 == list.size()) {
                System.out.println("仓库告急！");
                semaphore.release();
                return;
            }
            list.remove(0);
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static int CONSUME = 0;
    public static int PRODUCE = 1;
    public static void operation(int type) {
        try {
            semaphore.acquire();
            if (PRODUCE == type) {
                if (MAX == list.size()) {
                    System.out.println("仓库爆满！");
                }else {
                    list.add(1);
                    System.out.println(Thread.currentThread().getName() + "生产...仓库剩余：" + Store.list.size());
                }
            } else {
                if (0 == list.size()) {
                    System.out.println("仓库告急！");
                } else {
                    list.remove(0);
                    System.out.println(Thread.currentThread().getName() + "消费...仓库剩余：" + Store.list.size());
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
